package com.tanhua.manage.service;

import cn.hutool.core.util.StrUtil;
import com.tanhua.manage.enums.QueryType;
import com.tanhua.manage.mapper.SummaryMapper;
import com.tanhua.manage.pojo.AnalysisByDay;
import com.tanhua.manage.pojo.AnalysisByMon;
import com.tanhua.manage.vo.SummaryVo;
import com.tanhua.manage.vo.UsersDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.DateFormatter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SummaryService {
    @Autowired
    private SummaryMapper summaryMapper;
    //查询概要统计数据
    public SummaryVo querySummaryVo(String recordDate) throws ParseException {
        AnalysisByDay analysisByDay = summaryMapper.queryAnalysisByDay(recordDate);
        SummaryVo summaryVo = new SummaryVo();

        //计算累计用户数，迭代计算，今日累计用户数 = 新增用户+前一天累计用户
        //给定初始日期的累计用户
        Integer sumStart = sumUser("2018-01-01");
        sumStart = 717;
        summaryVo.setCumulativeUsers(sumUser(recordDate));//累计用户
        summaryVo.setActivePassMonth(sumActive(pastDay(recordDate, 30)));//过去30天活跃用户
        summaryVo.setActivePassWeek(sumActive(pastDay(recordDate, 7)));//过去7天活跃用户

        //昨天的日期、前天的日期
        String yesterday = getPastDate(1, (new SimpleDateFormat("yyyy-MM-dd")).parse(recordDate));
        String dayBeforeYst = getPastDate(2, (new SimpleDateFormat("yyyy-MM-dd")).parse(recordDate));
        Integer newToday = analysisByDay.getNumRegistered();
        summaryVo.setNewUsersToday(newToday);//今日新增用户
        //计算新增用户涨跌率
        Integer newYesterday = summaryMapper.queryAnalysisByDay(yesterday).getNumRegistered();
        Integer newRate = (newToday - newYesterday)/newYesterday;
        summaryVo.setNewUsersTodayRate(newRate);//今日新增用户涨跌率，单位百分数，正数为涨，负数为跌
        Integer loginToday = analysisByDay.getNumLogin();
        summaryVo.setLoginTimesToday(loginToday);//今日登录次数
        //计算今日登录次数涨跌率
        Integer loginYesterday = summaryMapper.queryAnalysisByDay(yesterday).getNumLogin();
        Integer loginRate = (loginToday - loginYesterday)/loginYesterday;
        summaryVo.setLoginTimesTodayRate(loginRate);//今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
        Integer activeToday = analysisByDay.getNumActive();
        summaryVo.setActiveUsersToday(activeToday);//今日活跃用户
        Integer activeYesterday = summaryMapper.queryAnalysisByDay(yesterday).getNumActive();
        summaryVo.setActiveUsersYesterday(activeYesterday);//昨日活跃用户
        //计算今日活跃用户涨跌率
        Integer activeRateToday = (activeToday - activeYesterday)/activeYesterday;
        summaryVo.setActiveUsersTodayRate(activeRateToday);//今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        //计算昨日活跃用户涨跌率
        Integer activeBeforeYst = summaryMapper.queryAnalysisByDay(dayBeforeYst).getNumActive();
        Integer activeRateYst = (activeYesterday - activeBeforeYst)/activeBeforeYst;
        summaryVo.setActiveUsersYesterdayRate(activeRateYst);//昨日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        //计算过去7天平均日使用时长
        //TODO 数据表中没有使用时长相关的数据，暂时没想到如何查询，直接写死
        summaryVo.setUseTimePassWeek(688);//过去7天平均日使用时长，单位秒

        return summaryVo;

    }
    //查询一段时间内每个月的新增、活跃用户、次日留存率,包括去年和今年的全部数据
    public UsersDataVo queryUsersDataVo(Date sd, Date ed, Integer type){
        UsersDataVo usersDataVo = new UsersDataVo();
        List<Map<String, Integer>> lastYear = new ArrayList<Map<String, Integer>>();
        List<Map<String, Integer>> thisYear = new ArrayList<Map<String, Integer>>();
        //判断起始和结束日期是否在同一年
        //不在同一年，则区分thisYear和lastYear
        if (sd.getYear() < ed.getYear()){
            //新增用户查询
            if (type == QueryType.REGISTERED.getType()){
                List<AnalysisByMon> thisYearMonList = this.summaryMapper.queryRegByMon(new Date(ed.getYear(),1,1), ed);
                for (AnalysisByMon analysisByMon : thisYearMonList) {
                    Map<String, Integer> map = new HashMap<>();
                    map.put(analysisByMon.getMonth().toString(), analysisByMon.getNumReg());
                    thisYear.add(map);
                }
                usersDataVo.setThisYear(thisYear.toArray());
                List<AnalysisByMon> lastYearMonList = this.summaryMapper.queryRegByMon(sd, new Date(sd.getYear(),12,31));
                for (AnalysisByMon analysisByMon : lastYearMonList) {
                    Map<String, Integer> map = new HashMap<>();
                    map.put(analysisByMon.getMonth().toString(), analysisByMon.getNumReg());
                    lastYear.add(map);
                }
                usersDataVo.setLastYear(lastYear.toArray());
            }
            //活跃用户查询
            if (type == QueryType.ACTIVE.getType()){
                List<AnalysisByMon> thisYearMonList = this.summaryMapper.queryActByMon(new Date(ed.getYear(),1,1), ed);
                for (AnalysisByMon analysisByMon : thisYearMonList) {
                    Map<String, Integer> map = new HashMap<>();
                    map.put(analysisByMon.getMonth().toString(), analysisByMon.getNumAct());
                    thisYear.add(map);
                }
                usersDataVo.setThisYear(thisYear.toArray());
                List<AnalysisByMon> lastYearMonList = this.summaryMapper.queryActByMon(sd, new Date(sd.getYear(),12,31));
                for (AnalysisByMon analysisByMon : lastYearMonList) {
                    Map<String, Integer> map = new HashMap<>();
                    map.put(analysisByMon.getMonth().toString(), analysisByMon.getNumAct());
                    lastYear.add(map);
                }
                usersDataVo.setLastYear(lastYear.toArray());
            }
            //次日留存数查询
            if (type == QueryType.RETENTION.getType()){
                List<AnalysisByMon> thisYearMonList = this.summaryMapper.queryRetByMon(new Date(ed.getYear(),1,1), ed);
                for (AnalysisByMon analysisByMon : thisYearMonList) {
                    Map<String, Integer> map = new HashMap<>();
                    map.put(analysisByMon.getMonth().toString(), analysisByMon.getNumRet());
                    thisYear.add(map);
                }
                usersDataVo.setThisYear(thisYear.toArray());
                List<AnalysisByMon> lastYearMonList = this.summaryMapper.queryRetByMon(sd, new Date(sd.getYear(),12,31));
                for (AnalysisByMon analysisByMon : lastYearMonList) {
                    Map<String, Integer> map = new HashMap<>();
                    map.put(analysisByMon.getMonth().toString(), analysisByMon.getNumRet());
                    lastYear.add(map);
                }
                usersDataVo.setLastYear(lastYear.toArray());
            }
            //在同一年
        }else if (sd.getYear() == ed.getYear()){
            //新增用户查询
            if (type == QueryType.REGISTERED.getType()){
                List<AnalysisByMon> thisYearMonList = this.summaryMapper.queryRegByMon(sd, ed);
                for (AnalysisByMon analysisByMon : thisYearMonList) {
                    Map<String, Integer> map = new HashMap<>();
                    map.put(analysisByMon.getMonth().toString(), analysisByMon.getNumReg());
                    thisYear.add(map);
                }
                usersDataVo.setThisYear(thisYear.toArray());
                usersDataVo.setLastYear(thisYear.toArray());
            }
            //活跃用户查询
            if (type == QueryType.ACTIVE.getType()){
                List<AnalysisByMon> thisYearMonList = this.summaryMapper.queryActByMon(sd, ed);
                for (AnalysisByMon analysisByMon : thisYearMonList) {
                    Map<String, Integer> map = new HashMap<>();
                    map.put(analysisByMon.getMonth().toString(), analysisByMon.getNumAct());
                    thisYear.add(map);
                }
                usersDataVo.setThisYear(thisYear.toArray());
                usersDataVo.setLastYear(thisYear.toArray());
            }
            //次日留存数查询
            if (type == QueryType.RETENTION.getType()){
                List<AnalysisByMon> thisYearMonList = this.summaryMapper.queryRetByMon(sd, ed);
                for (AnalysisByMon analysisByMon : thisYearMonList) {
                    Map<String, Integer> map = new HashMap<>();
                    map.put(analysisByMon.getMonth().toString(), analysisByMon.getNumRet());
                    thisYear.add(map);
                }
                usersDataVo.setThisYear(thisYear.toArray());
                usersDataVo.setLastYear(thisYear.toArray());
            }
        }
        return usersDataVo;
    }
    /**
     * 获取过去第几天的日期
     *
     * @param past
     * @return
     */
    private String getPastDate(int past, Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - past);
        Date today = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String result = sdf.format(today);
        return result;
    }
    /**
     * 获取过去N天内的日期数组
     * @return  日期数组
     */
    private ArrayList<String> pastDay(String time, Integer N){
        ArrayList<String> pastDaysList = new ArrayList<>();
        try {
            //我这里传来的时间是个string类型的，所以要先转为date类型的。
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(time);
            for (int i = N-1; i >= 0; i--) {
                pastDaysList.add(getPastDate(i,date));
            }
        }catch (ParseException e){
            e.printStackTrace();
        }
        return pastDaysList;
    }
    /**
     * 计算N天内活跃用户总数
     *
     */
    private Integer sumActive(ArrayList<String> pastDayList) {
        Integer activeSum = 0;
        for (String date : pastDayList) {
            AnalysisByDay analysisByDay = summaryMapper.queryAnalysisByDay(date);
            activeSum += analysisByDay.getNumActive();
        }
        return activeSum;
    }
    private Integer sumUser(String recordDate) {
        Integer userSum = 0;
        Date today = new Date();
        //今天的的日期
        try {
            today = (new SimpleDateFormat("yyyy-MM-dd")).parse(recordDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //今日累计用户数 = 新增用户+前一天累计用户
        Integer sumDayBefore = sumUser(getPastDate(1, today));
        if (sumDayBefore != 0) {
            userSum += sumDayBefore + summaryMapper.queryAnalysisByDay(recordDate).getNumRegistered();
        }else {
            System.out.println("数据查询错误");
        }

        return userSum;
    }
/*
        private Long id; //主键id
        private String date; //日期
        private Integer numRegistered; //新注册用户数
        private Integer numActive; //活跃用户数
        private Integer numLogin; //登陆次数
        private Integer numRetention1d; // 次日留存用户数
        private Integer created; //创建时间
        private Integer updated; //更新时间

        private Integer cumulativeUsers; //累计用户
        private Integer activePassMonth; //过去30天活跃用户
        private Integer activePassWeek; //过去7天活跃用户
        private Integer newUsersToday; //今日新增用户
        private Integer newUsersTodayRate; //今日新增用户涨跌率，单位百分数，正数为涨，负数为跌
        private Integer loginTimesToday; //今日登录次数
        private Integer loginTimesTodayRate; //今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
        private Integer activeUsersToday; //今日活跃用户
        private Integer activeUsersTodayRate; //今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        private Integer useTimePassWeek; //过去7天平均日使用时长，单位秒
        private Integer activeUsersYesterday; //昨日活跃用户
        private Integer activeUsersYesterdayRate; //昨日活跃用户涨跌率，单位百分数，正数为涨，负数为跌*/
}
